package Server;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/11/9 20:45
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String ip,int port) throws SocketException {
        socket = new DatagramSocket();
        serverIP = ip;
        serverPort = port;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
            //读取控制台的输入
            while (true) {
                System.out.println("->");
                String request = scanner.next();
                //2.把用户输入，构成一个 UDP 请求，并发送
                DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                        InetAddress.getByName(serverIP), serverPort);
                socket.send(requestPacket);
                //3.从服务器读取数据，并解析
                DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
                socket.receive(responsePacket);
                String response = new String(responsePacket.getData(), 0, responsePacket.getLength(),
                        "UTF-8");
                System.out.printf("req: %s,resp: %s\n",request,response);
            }
        }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
    }
